//
//  PhotosetViewController.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-19.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PhotosetViewController.h"


@implementation PhotosetViewController

@synthesize photoID;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.title = (NSLocalizedStringFromTable(@"PHOTOSET",@"main",@""));
	
	photosets = [[NSMutableArray alloc] init];
	
	selectIndex = -1;
	
	[NSThread detachNewThreadSelector:@selector(loadPhotosets:) toTarget:self withObject:nil];
	
	// 居中设置
	
	CGFloat w = self.view.frame.size.width;
	CGFloat h = self.view.frame.size.height;
	
	CGFloat sw = active.frame.size.width;
	CGFloat sh = active.frame.size.height;
	
	CGFloat sx = (w - sw)/2;
	CGFloat sy = (h - sh)/2 - 50;
	
	[active setFrame:CGRectMake(sx, sy, sw, sh)];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark -
#pragma mark Action
/**
 * 添加新的图片集
 */
-(IBAction)addPhotoSet:(id)sender{
	// TODO 进行图像集创建
}

-(IBAction)uploadModify:(id)sender{
	// TODO 添加选中的图像集
	if(self.photoID){
		if([photosets count] > 0){
			if(selectIndex > -1){
				if(!loading){
					[NSThread detachNewThreadSelector:@selector(addPhotoToSet:) toTarget:self withObject:nil];
				}
			}
		}
	}
}

-(void)addPhotoToSet:(id)arg{
	NSLog(@"Add Photo to Set");
	loading = YES;
	PhotosetInfo *psi = (PhotosetInfo *)[photosets objectAtIndex:selectIndex];
	NSString *psid = psi.setID;
	DataManager *dm = [DataManager sharedDataManager];
	BOOL bOK = [dm addPhotoToSet:self.photoID toSet:psid];
	NSString *aTitle = nil;
	NSString *aMessage = nil;
	NSString *aCancel = (NSLocalizedStringFromTable(@"OK",@"main",@""));
	if(bOK){
		// TODO 上传成功
		aTitle = (NSLocalizedStringFromTable(@"OK",@"main",@""));
		aMessage  = (NSLocalizedStringFromTable(@"PHOTO_TO_SET_SUCCESS",@"main",@""));
	}else{
		// TODO 上传失败
		aTitle = (NSLocalizedStringFromTable(@"ERROR",@"main",@""));
		aMessage  = (NSLocalizedStringFromTable(@"PHOTO_TO_SET_FAILD",@"main",@""));
	}
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle message:aMessage delegate:nil cancelButtonTitle:aCancel otherButtonTitles:nil];
	[alert show];
	[alert release];
	loading = NO;
}

#pragma mark -
#pragma mark Photoset Info loading
-(void)loadPhotosets:(id)arg{
	loading = YES;
	DataManager *dm = [DataManager sharedDataManager];
	if([dm isAuthorized]){
		// TODO 显示进度
		[self performSelectorOnMainThread:@selector(startActive:) withObject:nil waitUntilDone:NO];
		NSArray *ps = [dm getPhotosetsByID:dm.userId];
		if(ps){
			int con = [ps count];
			if(con > 0){
				// [photosets removeAllObjects];
				[photosets addObjectsFromArray:ps];
				[self performSelectorOnMainThread:@selector(reDisplay:) withObject:nil waitUntilDone:YES];
			}
		}
		[active stopAnimating];
		[active removeFromSuperview];
	}
	loading = NO;
}

-(void)startActive:(id)arg{	
	[self.view addSubview:active];
	[active startAnimating];
}


-(void)reDisplay:(id)arg{
	[tableView reloadData];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)table {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [photosets count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		// 针对不同的目标平台进行适配
#ifndef __IPHONE_3_0
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
#else
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
#endif
    }
	
	// cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	int section = indexPath.section;
	int row = indexPath.row;
	
	if(section == 0){
		// TODO 显示 照片集
		PhotosetInfo *pinfo = (PhotosetInfo *)[photosets objectAtIndex:row];
#ifndef __IPHONE_3_0
		cell.text = pinfo.title;
#else
		cell.textLabel.text = pinfo.title;
#endif
	}
	
	if(row == selectIndex){
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	}else{
		cell.accessoryType = UITableViewCellAccessoryNone;
	}
    
    // Set up the cell...
	
    return cell;
}


- (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	selectIndex = indexPath.row;
	
	[self reDisplay:nil];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)table canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)table commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)table moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)table canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
	[photosets release];
	[active release];
    [super dealloc];
}


@end

